﻿/*
 * @Author: ws.s 
 * @Date: 2021-05-15 18:00:37 
 * @Last Modified by:   ws.s 
 * @Last Modified time: 2021-05-15 18:00:37 
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using WssUtils;

/// <summary>
/// 资源下载管理器
/// </summary>
public class DownloadManager : SingletonMonoBehaviour<DownloadManager>
{

    public string ConvertBase64String(string base64Str)
    {
        byte[] outputb = Convert.FromBase64String(base64Str);
        string orgStr = Encoding.Default.GetString(outputb);
        return orgStr;
    }

    /// <summary>
    /// 下载图片
    /// </summary>
    /// <param name="url"></param>
    /// <param name="callback"></param>
    public static void LoadTexture(string url, Action<bool, Texture2D> callback)
    {
        Instance.StartCoroutine(Instance._LoadTexture(url, callback));
    }

    /// <summary>
    /// 下载文本文件
    /// </summary>
    /// <param name="url"></param>
    /// <param name="callback"></param>
    public static void LoadText(string url, Action<bool, string> callback)
    {
        Instance.StartCoroutine(Instance._LoadText(url, callback));
    }

    IEnumerator _LoadTexture(string url, Action<bool, Texture2D> callback)
    {
        UnityWebRequest wr = new UnityWebRequest(url);
        DownloadHandlerTexture texDl = new DownloadHandlerTexture(true);
        wr.downloadHandler = texDl;
        yield return wr.SendWebRequest();
        if (!wr.isNetworkError)
        {
            callback.Invoke(true, texDl.texture);
        }
        else
        {
            callback.Invoke(false, null);
        }
    }

    IEnumerator _LoadText(string url, Action<bool, string> callback)
    {
        Uri uri = new Uri(url);
        UnityWebRequest uwr = new UnityWebRequest(uri);
        DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
        uwr.downloadHandler = dH;
        uwr.timeout = 5;
        yield return uwr.SendWebRequest();
        if (uwr.isHttpError || uwr.isNetworkError)             //如果其 请求失败，或是 网络错误
        {
            Debug.LogError(uwr.error); //打印错误原因
            callback.Invoke(false, "");
        }
        else //请求成功
        {
            callback.Invoke(true, uwr.downloadHandler.text);
        }
    }

}
